"""
CrewAI 股票分析智能体协作系统 - 主程序
展示 CrewAI 的核心功能和最佳实践
"""
from crew_flow import CrewAIStockFlow
from dotenv import load_dotenv
from colorama import init, Fore, Style
import json
import os
import sys
from typing import Dict, Any


def display_crewai_features():
    """展示 CrewAI 功能特性"""
    print(Fore.CYAN + Style.BRIGHT + "\n🔥 === CrewAI 功能展示 ===")
    features = [
        "🤖 智能体协作 - Agent 之间的任务协调和信息共享",
        "📋 任务管理 - Task 定义、依赖关系和执行顺序",
        "🛠️ 工具集成 - 自定义工具和 LangChain 工具支持",
        "🧠 记忆系统 - 短期和长期记忆管理",
        "🔄 流程控制 - 顺序执行和并行执行模式",
        "📊 结果聚合 - 多任务结果的智能整合",
        "🎯 目标导向 - 基于目标的任务规划",
        "⚡ 高效协作 - 智能体间的高效协作机制"
    ]
    
    for feature in features:
        print(Fore.YELLOW + f"  {feature}")
    
    print(Fore.CYAN + Style.BRIGHT + "\n本项目展示了以上所有 CrewAI 核心功能的实际应用！")


def check_crewai_environment():
    """检查 CrewAI 环境配置"""
    print(Fore.CYAN + "\n🔍 检查 CrewAI 环境...")
    
    try:
        # 检查 CrewAI 相关包
        import crewai
        import crewai_tools
        print(Fore.GREEN + "✅ CrewAI 已安装")
        print(Fore.GREEN + "✅ CrewAI Tools 已安装")
        
        # 检查 LangChain（CrewAI 依赖）
        import langchain
        import langchain_openai
        print(Fore.GREEN + "✅ LangChain 支持已就绪")
        
        # 检查配置文件
        config_path = os.path.join(os.path.dirname(__file__), "config.json")
        if os.path.exists(config_path):
            print(Fore.GREEN + "✅ 配置文件存在")
        else:
            print(Fore.RED + "❌ 配置文件缺失")
            return False
        
        # 检查环境变量
        load_dotenv()
        
        with open(config_path, "r", encoding="utf-8") as f:
            config = json.load(f)
        
        # 检查智能体配置
        agents_config = config.get("agents", {})
        for agent_name, agent_info in agents_config.items():
            api_key = agent_info.get("app_key")
            if api_key and not api_key.startswith("your_"):
                print(Fore.GREEN + f"✅ {agent_info['name']} API Key 已配置")
            else:
                print(Fore.YELLOW + f"⚠️ {agent_info['name']} API Key 需要配置")
        
        # 检查 Tushare Token
        tushare_token = config.get("tushare_token")
        if tushare_token and not tushare_token.startswith("your_"):
            print(Fore.GREEN + "✅ Tushare Token 已配置")
        else:
            print(Fore.YELLOW + "⚠️ Tushare Token 需要配置")
        
        return True
        
    except ImportError as e:
        print(Fore.RED + f"❌ CrewAI 包缺失: {e}")
        print(Fore.YELLOW + "请运行: pip install -r requirements.txt")
        return False
    except Exception as e:
        print(Fore.RED + f"❌ 环境检查失败: {e}")
        return False


def interactive_demo():
    """交互式演示"""
    print(Fore.CYAN + Style.BRIGHT + "\n🎮 === 交互式演示模式 ===")
    
    crew_flow = None
    
    while True:
        print(Fore.CYAN + "\n请选择演示选项:")
        print("1. 🚀 运行完整的智能体协作流程")
        print("2. 📊 查看智能体信息")
        print("3. 🔧 运行简化分析（快速测试）")
        print("4. 📈 分析自定义股票")
        print("5. 🎯 查看 CrewAI 特性")
        print("6. 🏃 退出演示")
        
        choice = input(Fore.GREEN + "\n请输入选项 (1-6): ").strip()
        
        if choice == "1":
            run_full_workflow()
        elif choice == "2":
            show_agent_info()
        elif choice == "3":
            run_simple_analysis()
        elif choice == "4":
            analyze_custom_stock()
        elif choice == "5":
            display_crewai_features()
        elif choice == "6":
            print(Fore.CYAN + "👋 感谢使用 CrewAI 智能体协作系统！")
            break
        else:
            print(Fore.RED + "❌ 无效选项，请重新选择")


def run_full_workflow():
    """运行完整工作流"""
    print(Fore.CYAN + "\n🚀 启动完整的 CrewAI 智能体协作流程...")
    
    try:
        crew_flow = CrewAIStockFlow()
        stock_code = "600519.SH"  # 贵州茅台
        print(Fore.GREEN + f"📈 分析股票: {stock_code} (贵州茅台)")
        crew_flow.run(stock_code)
        
    except Exception as e:
        print(Fore.RED + f"❌ 工作流执行失败: {e}")


def show_agent_info():
    """显示智能体信息"""
    print(Fore.CYAN + "\n📊 CrewAI 智能体信息...")
    
    try:
        crew_flow = CrewAIStockFlow()
        crew_flow.get_agent_info()
        
    except Exception as e:
        print(Fore.RED + f"❌ 获取智能体信息失败: {e}")


def run_simple_analysis():
    """运行简化分析"""
    print(Fore.CYAN + "\n🔧 运行简化分析模式...")
    
    try:
        crew_flow = CrewAIStockFlow()
        stock_code = "600519.SH"
        print(Fore.GREEN + f"📈 快速分析股票: {stock_code}")
        crew_flow.run_simple_analysis(stock_code)
        
    except Exception as e:
        print(Fore.RED + f"❌ 简化分析失败: {e}")


def analyze_custom_stock():
    """分析自定义股票"""
    print(Fore.CYAN + "\n📈 自定义股票分析...")
    
    stock_code = input(Fore.GREEN + "请输入股票代码 (例如: 000001.SZ): ").strip()
    
    if not stock_code:
        print(Fore.RED + "❌ 股票代码不能为空")
        return
    
    try:
        crew_flow = CrewAIStockFlow()
        crew_flow.run(stock_code)
        
    except Exception as e:
        print(Fore.RED + f"❌ 股票分析失败: {e}")


def compare_with_langchain():
    """与 LangChain 版本对比"""
    print(Fore.CYAN + Style.BRIGHT + "\n📊 === CrewAI vs LangChain 对比 ===")
    
    comparison = """
    ┌─────────────────┬──────────────────────┬──────────────────────┐
    │     特性        │      CrewAI          │     LangChain        │
    ├─────────────────┼──────────────────────┼──────────────────────┤
    │ 智能体协作      │ 原生支持，内置协调   │ 需要自定义实现       │
    │ 任务管理        │ Task 对象，依赖管理  │ Chain/Runnable组合   │
    │ 工具集成        │ 内置工具框架         │ Tool 接口            │
    │ 记忆系统        │ 内置短期/长期记忆    │ Memory 组件          │
    │ 流程控制        │ Sequential/Parallel  │ Chain 组合           │
    │ 代码复杂度      │ 更简洁，声明式       │ 更灵活，编程式       │
    │ 学习曲线        │ 较平缓               │ 较陡峭               │
    │ 生态系统        │ 专注于多智能体       │ 更广泛的 AI 应用     │
    └─────────────────┴──────────────────────┴──────────────────────┘
    """
    print(Fore.YELLOW + comparison)
    
    print(Fore.CYAN + "\n💡 总结：")
    print(Fore.WHITE + "• CrewAI 更适合快速构建多智能体协作系统")
    print(Fore.WHITE + "• LangChain 提供更底层的控制和更广泛的功能")
    print(Fore.WHITE + "• 两者可以结合使用，CrewAI 底层使用 LangChain")


def main():
    """主函数"""
    init(autoreset=True)
    
    print(Fore.CYAN + Style.BRIGHT + "=" * 60)
    print(Fore.CYAN + Style.BRIGHT + "🤖 CrewAI 股票分析智能体协作系统")
    print(Fore.CYAN + Style.BRIGHT + "=" * 60)
    
    # 显示 CrewAI 功能特性
    display_crewai_features()
    
    # 检查环境
    if not check_crewai_environment():
        print(Fore.RED + "\n❌ 环境检查失败，请检查配置后重试")
        return
    
    print(Fore.GREEN + "\n✅ 环境检查通过，系统准备就绪！")
    
    # 询问运行模式
    print(Fore.CYAN + "\n请选择运行模式:")
    print("1. 🚀 快速演示 (自动运行)")
    print("2. 🎮 交互式演示")
    print("3. 📊 对比 LangChain")
    
    mode = input(Fore.GREEN + "请输入选项 (1-3): ").strip()
    
    if mode == "1":
        print(Fore.CYAN + "\n🚀 启动快速演示模式...")
        run_full_workflow()
    elif mode == "2":
        interactive_demo()
    elif mode == "3":
        compare_with_langchain()
        # 显示对比后询问是否运行演示
        choice = input(Fore.GREEN + "\n是否运行 CrewAI 演示? (y/n): ").strip().lower()
        if choice == 'y':
            run_full_workflow()
    else:
        print(Fore.YELLOW + "使用默认快速演示模式...")
        run_full_workflow()
    
    print(Fore.CYAN + Style.BRIGHT + "\n🎉 感谢使用 CrewAI 智能体协作系统！")


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print(Fore.YELLOW + "\n\n👋 用户中断，程序退出")
    except Exception as e:
        print(Fore.RED + f"\n❌ 程序异常退出: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
